package com.joinway.extension.socket.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joinway.extension.socket.bean.SessionConfig;
import com.joinway.extension.socket.handler.FrameDataHandler;
import com.joinway.extension.socket.handler.IMessageProcessor;
import com.joinway.extension.socket.server.codec.CodecFactory;

public class FrameDataServer<T> {

	private final static Logger log = LoggerFactory.getLogger(FrameDataServer.class);
	
	protected IoAcceptor acceptor;
	
	protected FrameDataHandler<T> handler;
	
	protected SessionConfig config;
	
	protected CodecFactory factory;
	
	public FrameDataServer(IoAcceptor acceptor, IMessageProcessor<T> processor, ProtocolDecoder decoder, ProtocolEncoder encoder, SessionConfig config){
		this.acceptor = acceptor;
		this.handler = new FrameDataHandler<>(processor);
		this.config = config;
		this.factory = new CodecFactory(decoder, encoder);
	}
	
	public FrameDataServer(IoAcceptor acceptor, FrameDataHandler<T> handler, ProtocolDecoder decoder, ProtocolEncoder encoder, SessionConfig config){
		this.acceptor = acceptor;
		this.handler = handler;
		this.config = config;
		this.factory = new CodecFactory(decoder, encoder);
	}

	public void start() throws IOException{
		acceptor.getSessionConfig().setReadBufferSize(config.getReadBuffer());
		acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(factory));
		acceptor.setHandler(handler);
		acceptor.bind(new InetSocketAddress(config.getPort()));
		
		log.info("frame data server is listening port {}", config.getPort());
	}

}
